<?php

/**
 * Implementation of hook_footer().
 */
function imce_footer() {
  if (user_access('access imce')) {
    $header = drupal_get_js();
    //set imce if tinymce is in action
    if (!imce_integrate('tinymce', 'check') && module_exists('tinymce') && variable_get('imce_settings_tinymce', 1) && strpos($header, 'tiny_mce')) {
      $output .= '<script type="text/javascript" src="'. base_path() . drupal_get_path('module', 'imce') .'/imce_set_tinymce.js' .'"></script>';
    }
    //set imce if fckeditor is in action
    if (!imce_integrate('fck', 'check') && module_exists('fckeditor') && variable_get('imce_settings_fck', 0) && strpos($header, 'fckeditor.js')) {
      $output .= '<script type="text/javascript" src="'. base_path() . drupal_get_path('module', 'imce') .'/imce_set_fck.js' .'"></script>';
    }
    if ($output) {
      return '<script type="text/javascript"> var imceBrowserURL = "'.url('imce/browse').'"; </script>'. $output;
    }
  }
}


/**
 * Image Browser.
 */
function imce_browse() {
  $set = (object) imce_settings_user();
  $private = variable_get('file_downloads', '')==FILE_DOWNLOADS_PRIVATE;
  $syspath = file_directory_path();
  $basepath = base_path();
  $imcepath = $basepath. drupal_get_path('module', 'imce');
  $header = array(array('data'=>t('filename'), 'class'=>'filename'), array('data'=>t('size'), 'class'=>'size'), array('data'=>t('dimensions'), 'class'=>'dimensions'), array('data'=>t('date'), 'class'=>'date'), array('data'=>t('operations'), 'class'=>'operations'));
  $token = drupal_get_token('imce');

  //file list
  $directory = imce_scan_directory($set->dir);
  //prevent quota theft by multiple sessions.
  if ($_SESSION['imcelatest'] && $directory['size']>$set->quota*1024 && !$set->nolimit) {
    $directory['size'] -= filesize($_SESSION['imcelatest']);
    @unlink($_SESSION['imcelatest']);
    unset($directory['files'][$_SESSION['imcelatest']], $_SESSION['imcelatest']);
    drupal_set_message(t('File was deleted due to quota exceed!'), 'error');
  }
  foreach ($directory['files'] as $path=>$file) {
    $rows[] = array(array('data' => $file['f'], 'class' => 'filename'),
      array('data' => format_size($file['s']), 'class' => 'size', 'id' => 's-'.$file['s']),
      array('data' => $file['w'].'x'.$file['h'], 'class' => 'dimensions'),
      array('data' => date('Y-m-d', $file['d']), 'class' => 'date', 'id' => 'd-'.$file['d'], 'title' => date('H:i:s', $file['d'])),
      array('data' => $set->delete ? imce_delete_form($file['f']) : '', 'class' => 'operations'),
      array('data' => $set->rename ? imce_rename_form($file['f']) : '', 'class' => 'operations'),
    );
  }
  if (!isset($rows)) {
    $rows = array(array('<div class="messages">'.t('Directory is empty.').'</div>'));
  }
  $_SESSION['imcetotal'] = $directory['size'];

  //folder list
  if ($set->subnav) {
    foreach ($directory['folders'] as $folder) {
      $foptions .= '<option value="'.$folder.'">/'.$folder.'</option>';
    }
    $subdir = $set->root != $set->dir;
    if ($foptions||$subdir) {
      $foptions = ' <form action="'.url('imce/dir').'" name="dirform" id="dirform" method="post"><select name="dirname" id="dirname">'. ($subdir ? '<option value="..">'. t('Up') .'</option>' : '') .'<option value="/" selected="selected">/</option>'.$foptions.'</select><input type="submit" name="op" id="dirop" value="'.t('Go').'" /><input type="hidden" name="token" value="'. $token .'" /></form>';
    }
  }

  //upload form
  if ($set->upload) {
    $uploadform = '<form action="'.url('imce/upload').'" method="post" id="uploadform" enctype="multipart/form-data">
  <div class="form-item"><p>Files will be uploaded into the current folder as shown above.</p>'.
  '<input type="file" name="thefile" id="thefile" size="30" /></div>'.
  ($set->nolimit ? '<label for="scale" class="form-item"><input type="checkbox" checked="checked" id="scale" name="scale" />'.t('Scale if necessary').'</label>' : ($set->scale ? '<input type="hidden" value="1" name="scale" />' : '')).
  ($set->twidth&&$set->theight ? '<label for="thumb" class="form-item"><input type="checkbox" checked="checked" id="thumb" name="thumb" />'.t('Create thumbnail').' ('. $set->twidth .'x'. $set->theight .')</label>' : '').
  '<div class="form-item"><input type="submit" name="submit" value="'.t('Upload File').'" /></div>'.
  '<input type="hidden" name="token" value="'. $token .'" />'.
'</form>';
//<div class="limits">'.  ($set->nolimit ? t('Dimensions for scaling') .' = <strong>'. $set->width .'x'. $set->height .'</strong>, '. t('Quota') .' = <strong>'. format_size($_SESSION['imcetotal']).'</strong>/'.t('Unlimited') : '<strong>'. t('Limits') .'</strong>: '. t('File size') .' = <strong>'. $set->filesize .' KB</strong>, '. t('Dimensions') .' = <strong>'. $set->width .'x'. $set->height .'</strong>, '. t('Quota') .' = <strong>'. format_size($_SESSION['imcetotal']) .'</strong>/'. $set->quota .' KB').'</div>';
  }
  //resize form
  if ($set->resize) {
    $resizeform = '<form action="'.url('imce/resize').'" method="post" id="resizeform">
  <span id="resize-file-span">'.t('filename').':<input type="text" name="img_name" id="img_name" size="12" /></span>
  <div class="form-item">'.t('New Dimensions').':<input type="text" name="img_w" id="img_w" size="2" />x<input type="text" name="img_h" id="img_h" size="2" /></div>
  <label class="form-item" for="img_copy"><input type="checkbox" checked="checked" id="img_copy" name="img_copy" />'.t('Create a copy').'</label>
  <div class="form-item"><input type="submit" name="submit" value="'.t('Resize image').'" /></div>
  <input type="hidden" name="token" value="'. $token .'" />
</form>';
  }

  $title = t('Image Browser');
  $imceVars = 'var imceVar = [];
    imceVar["fileUrl"] = "'. imce_relative_url($set->dir) .'";
    imceVar["latestFile"] = "'. ($_SESSION['imcelatest'] ? imce_relative_url($_SESSION['imcelatest']) : '') .'";
    imceVar["confirmDel"] = "'. ($set->delete ? t('Are you sure want to delete this file?') : '') .'";
    imceVar["confirmRen"] = "'. ($set->rename ? t('New file name:') : '') .'";
    imceVar["viewText"] = "'.t('view').'";
    imceVar["basePath"] = "'. base_path() .'"; 
    imceVar["addText"] = "'.t('add').'";'. ($set->extras ? '
    imceVar["filterText"] = ["'.t('Display'). '", "'. t('all'). '", "'. t('images'). '", "'. t('non-images').'"];' : '');
  $jquery_path = $basepath .'misc/jquery.js';
  $extras = ($set->extras ? '<script type="text/javascript" src="'. $imcepath .'/imce_extras.js"></script>' : '');
  $headertable = theme('table', $header, array(), array('id'=>'headertable'));
  $bodydiv_title = ($set->extras ? t('Keyboard shortcuts').': '.t('UP(previous), DOWN(next), DELETE, INSERT(add)') : '');
  $bodydiv = theme('table', array(), $rows, array('id'=>'bodytable'));
  $info_div = t('Current folder') .': '. ($private&&$set->uid!=1 ? imce_relative_path($set->dir, $syspath) : $set->dir).($foptions ? $foptions : '').($_SESSION['imceuser'] ? '<div>'.t('User').': '.$_SESSION['imceuser']['name'].' - '.l(t('logout'), 'imce/logout').'</div>' : '');
  $status_messages = theme('status_messages');
  
  $output = <<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>$title</title>
    <script type="text/javascript">
    $imceVars
  </script>
    <script type="text/javascript" src="$jquery_path"></script>
    <script type="text/javascript" src="$imcepath/imce_browse.js"></script>$extras
    <style type="text/css" media="all">@import "$imcepath/imce.css";</style>
</head>
<body>
    <ul id="tabs">
      <li id="tab-select" class="active"><a href="javascript:;" onclick="imceSwitchTabs('select')">choose</a></li>
      <li id="tab-upload"><a href="javascript:;" onclick="imceSwitchTabs('upload')">upload new</a></li>
      <li id="tab-resize"><a href="javascript:;" onclick="imceSwitchTabs('resize')">resize</a></li>
    </ul>
    $status_messages
    <div id="info-div">$info_div</div>
    <div id="headerdiv">$headertable</div>
    <div id="bodydiv" title="$bodydiv_title">$bodydiv</div>
    <div id="uploadform" class="forms hidden">$uploadform</div>
    <div id="resizeform" class="forms hidden">$resizeform</div>
    <div id="imagepreview"></div>
</body>
</html>
EOT;
  unset($_SESSION['imcelatest']);
  print $output;
  exit();
}

/** render mini form button to rename this file */
function imce_rename_form($file)
{
$base_path = base_path();
$token = drupal_get_token('imce');
$h =<<<EOT
<form action="{$base_path}imce/rename/{$file}" method="POST">
<input type="hidden" name="token" value="$token">
<input type="hidden" name="newfilename" value="$file">
<input type="submit" value="rename">
</form>
EOT;
return $h;
}

function imce_delete_form($file)
{
$base_path = base_path();
$token = drupal_get_token('imce');
$h =<<<EOT
<form action="{$base_path}imce/delete/{$file}" method="POST">
<input type="hidden" name="token" value="$token">
<input type="submit" value="delete">
</form>
EOT;
return $h;
}

